/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package cn.tedu.luban.settle.webapi.service.impl;

import cn.tedu.luban.commons.pojo.order.dto.OrderMqDTO;
import cn.tedu.luban.settle.service.ISettleBillService;
import cn.tedu.luban.settle.service.ISettleEventService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendCallback;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class SettleEventServiceImpl implements ISettleEventService {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Autowired
    private ISettleBillService settleBillService;

    @Value("${mq.topic.settle-success-topic:settle-success-topic}")
    private String orderSettleTopic;

    @Override
    public void sendSettledEvent(OrderMqDTO orderMqDTO) {
        log.info("发送消息给财务，财务打款,通知结算，通知订单");
        //先修改结算状态
        try {
            //todo 模拟财务系统打款
            TimeUnit.SECONDS.sleep(5L);
            //执行结算状态的修改
            settleBillService.mockPayAndUpdateSettleBillStatus(orderMqDTO);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        //再发消息给order模块表示订单流程完成
        rocketMQTemplate.asyncSend(orderSettleTopic, orderMqDTO, new SendCallback() {
            @Override
            public void onSuccess(SendResult result) {
                log.info("发送mq成功, topic: {}, result:{}",
                        orderSettleTopic, result);
            }

            @Override
            public void onException(Throwable throwable) {
                //todo 发送失败后续处理
                log.error("发送mq失败, topic: {}, Throwable",
                        orderSettleTopic, throwable);
            }
        });
    }
}
